package com.joecy.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class HelloController {

    @HystrixCommand(fallbackMethod = "notService")
    @RequestMapping("/hello/{name}")
    public String index(@PathVariable String name) {
        if (name.length()>6) {
            throw new RuntimeException("服务出故障了！！");
        }
        return "Hello "+name+"，welcome to study spring-cloud hystrix！！";
    }

    public String notService(@PathVariable String name) {
       return  "Sorry, the waiter are unable to provide services to "+name+" at this time";
    }


    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/provider/discovery")
    public Object discovery(){
        List<String> list = discoveryClient.getServices();
        System.out.println(list);
        List<ServiceInstance> insList = discoveryClient.getInstances("spring-cloud-provider");
        for (ServiceInstance si:insList) {
            System.out.println(si.getHost() +"," + si.getServiceId() +"," +si.getPort() +"," +si.getUri() +"," +si.getMetadata());
        }
        return this.discoveryClient;
    }

}